<template>
	<view class="face-login-page">
		<!-- 自定义导航栏 -->
		<ob-navbar 
			title="人脸登录" 
			:show-back="true" 
			background-color="rgba(255, 255, 255, 0.95)"
			title-color="#333333"
			:border="true"
		/>
		
		<!-- 主要内容 -->
		<view class="content-container">
			<!-- 头部说明 -->
			<view class="header-section">
				<view class="icon-container">
					<text class="face-icon">👤</text>
				</view>
				<text class="main-title">人脸识别登录</text>
				<text class="sub-title">安全便捷，一拍即登</text>
			</view>
			
			<!-- 用户名输入区域 -->
			<view v-if="currentStep === 1" class="input-section">
				<view class="input-group">
					<text class="input-label">用户名</text>
					<input
						class="input-field"
						type="text"
						v-model="username"
						placeholder="请输入用户名"
						:class="{ 'input-error': usernameError }"
						@input="clearUsernameError"
					/>
					<text v-if="usernameError" class="error-text">{{ usernameError }}</text>
				</view>
			</view>

			<!-- 人脸识别状态 -->
			<view v-if="currentStep === 2" class="status-section">
				<view class="status-card" :class="statusClass">
					<view class="status-icon">
						<text v-if="loginStatus === 'idle'">📷</text>
						<text v-else-if="loginStatus === 'scanning'">🔍</text>
						<text v-else-if="loginStatus === 'success'">✅</text>
						<text v-else-if="loginStatus === 'failed'">❌</text>
					</view>
					<text class="status-text">{{ statusText }}</text>
					<text v-if="loginStatus === 'failed'" class="error-detail">{{ errorMessage }}</text>
				</view>
			</view>
			
			<!-- 操作按钮 -->
			<view class="action-section">
				<!-- 第一步：输入用户名 -->
				<button
					v-if="currentStep === 1"
					class="btn btn-primary"
					@click="goToFaceStep"
				>
					<text class="btn-icon">👤</text>
					<text>下一步</text>
				</button>

				<!-- 第二步：人脸识别 -->
				<button
					v-if="currentStep === 2 && (loginStatus === 'idle' || loginStatus === 'failed')"
					class="btn btn-primary start-btn"
					@click="startFaceLogin"
				>
					<text class="btn-icon">📷</text>
					<text>开始人脸识别</text>
				</button>

				<button
					v-if="currentStep === 2 && loginStatus === 'scanning'"
					class="btn btn-secondary cancel-btn"
					@click="cancelFaceLogin"
				>
					<text>取消识别</text>
				</button>
				
				<button 
					v-if="loginStatus === 'success'"
					class="btn btn-primary continue-btn"
					@click="goToHome"
				>
					<text class="btn-icon">🏠</text>
					<text>进入首页</text>
				</button>
			</view>
			
			<!-- 其他登录方式 -->
			<view class="alternative-section">
				<view class="divider">
					<view class="divider-line"></view>
					<text class="divider-text">其他登录方式</text>
					<view class="divider-line"></view>
				</view>
				
				<view class="alternative-buttons">
					<button class="btn btn-outline alt-btn" @click="goToPasswordLogin">
						<text class="btn-icon">🔑</text>
						<text>密码登录</text>
					</button>
				</view>
			</view>
			
			<!-- 注册提示 -->
			<view class="register-hint">
				<text class="hint-text">还没有账号？</text>
				<text class="hint-link" @click="goToRegister">立即注册</text>
			</view>

			<!-- 调试链接 -->
			<view class="debug-links">
				<text class="hint-link" @click="goToPureTest">纯HTML5测试</text>
				<text class="hint-text"> | </text>
				<text class="hint-link" @click="goToCaptureTest">拍照测试</text>
				<text class="hint-text"> | </text>
				<text class="hint-link" @click="goToCanvasTest">Canvas测试</text>
				<text class="hint-text"> | </text>
				<text class="hint-link" @click="goToDebug">完整调试</text>
			</view>
		</view>
		
		<!-- 人脸识别摄像头弹窗 -->
		<view v-if="showCameraModal" class="camera-modal">
			<view class="modal-overlay" @click="handleFaceCancel"></view>
			<view class="modal-content">
				<face-camera
					mode="login"
					@success="handleFaceSuccess"
					@cancel="handleFaceCancel"
					@error="handleFaceError"
				/>
			</view>
		</view>
		
		<!-- 加载提示 -->
		<ob-loading :visible="isLoading" text="正在验证..." />
	</view>
</template>

<script setup>
import { ref, reactive, computed, inject } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import FaceCamera from '../../components/face-recognition/face-camera.vue'
import authApi from '../../api/auth.js'

// 注入状态管理
const store = inject('$store')

// 响应式数据
const currentStep = ref(1) // 1: 输入用户名, 2: 人脸识别
const username = ref('')
const usernameError = ref('')
const isLoading = ref(false)
const loginStatus = ref('idle') // idle | scanning | success | failed
const errorMessage = ref('')
const showCameraModal = ref(false)

// 计算属性
const statusClass = computed(() => {
	return {
		'status-idle': loginStatus.value === 'idle',
		'status-scanning': loginStatus.value === 'scanning',
		'status-success': loginStatus.value === 'success',
		'status-failed': loginStatus.value === 'failed'
	}
})

const statusText = computed(() => {
	switch (loginStatus.value) {
		case 'idle':
			return '准备开始人脸识别'
		case 'scanning':
			return '正在进行人脸识别...'
		case 'success':
			return '识别成功，登录完成！'
		case 'failed':
			return '识别失败，请重试'
		default:
			return ''
	}
})

// 生命周期
onLoad(() => {
	// 检查是否支持人脸识别
	checkFaceLoginSupport()
})

// 方法
const validateUsername = () => {
	usernameError.value = ''

	if (!username.value.trim()) {
		usernameError.value = '请输入用户名'
		return false
	}

	if (username.value.trim().length < 3) {
		usernameError.value = '用户名至少3个字符'
		return false
	}

	return true
}

const clearUsernameError = () => {
	usernameError.value = ''
}

const goToFaceStep = () => {
	if (!validateUsername()) {
		return
	}

	currentStep.value = 2
	loginStatus.value = 'idle'
}

const checkFaceLoginSupport = () => {
	// 检查设备是否支持摄像头
	uni.getSystemInfo({
		success: (res) => {
			console.log('设备信息:', res)
			// 这里可以根据设备信息判断是否支持人脸识别
		},
		fail: (error) => {
			console.error('获取设备信息失败:', error)
		}
	})
}

const startFaceLogin = () => {
	loginStatus.value = 'scanning'
	errorMessage.value = ''

	// 打开摄像头弹窗
	showCameraModal.value = true
}

const cancelFaceLogin = () => {
	loginStatus.value = 'idle'

	// 关闭摄像头弹窗
	showCameraModal.value = false
}

const handleFaceSuccess = async (imageData) => {
	console.log('人脸拍摄成功，开始登录验证')

	// 关闭摄像头弹窗
	showCameraModal.value = false

	isLoading.value = true
	loginStatus.value = 'scanning'

	try {
		// 调用人脸登录API
		const response = await authApi.faceLogin({
			username: username.value.trim(),
			faceImagePath: imageData
		})

		console.log('人脸登录响应:', response)

		if (response && response.success) {
			// 登录成功
			const userInfo = {
				id: response.userId,
				username: response.username,
				nickname: response.nickname,
				loginType: 'face',
				similarity: response.similarity
			}

			// 保存用户信息和token到状态管理
			if (store && store.actions && store.actions.login) {
				store.actions.login(userInfo, response.accessToken, response.refreshToken)
			}

			loginStatus.value = 'success'

			uni.showToast({
				title: `登录成功 (相似度: ${Math.round(response.similarity * 100)}%)`,
				icon: 'success',
				duration: 2000
			})

			// 延迟跳转到首页
			setTimeout(() => {
				goToHome()
			}, 2000)
		} else {
			// 登录失败
			loginStatus.value = 'failed'

			let failMessage = response.message || '人脸验证失败'
			if (response.similarity !== undefined) {
				failMessage += ` (相似度: ${Math.round(response.similarity * 100)}%, 需要: 90%+)`
			}

			errorMessage.value = failMessage
			throw new Error(failMessage)
		}

	} catch (error) {
		console.error('人脸登录失败:', error)
		loginStatus.value = 'failed'

		// 处理不同的错误类型
		// 临时注释掉用户不存在的错误处理
		// if (error.message.includes('用户不存在')) {
		//	errorMessage.value = '用户不存在，请检查用户名'
		// } else
		if (error.message.includes('未录入人脸')) {
			errorMessage.value = '该用户未录入人脸信息，请先注册'
		} else if (error.message.includes('相似度不足')) {
			errorMessage.value = '人脸验证失败，相似度不足'
		} else {
			errorMessage.value = error.message || '登录失败，请重试'
		}

		uni.showToast({
			title: errorMessage.value,
			icon: 'none',
			duration: 3000
		})
	} finally {
		isLoading.value = false
	}
}

const handleFaceCancel = () => {
	loginStatus.value = 'idle'

	// 关闭摄像头弹窗
	showCameraModal.value = false
}

const handleFaceError = (error) => {
	console.error('人脸识别错误:', error)
	loginStatus.value = 'failed'
	errorMessage.value = error || '摄像头启动失败'

	// 关闭摄像头弹窗
	showCameraModal.value = false
	
	uni.showToast({
		title: errorMessage.value,
		icon: 'none',
		duration: 2000
	})
}

const getDeviceInfo = async () => {
	return new Promise((resolve) => {
		uni.getSystemInfo({
			success: (res) => {
				resolve({
					platform: res.platform,
					model: res.model,
					system: res.system,
					version: res.version
				})
			},
			fail: () => {
				resolve({})
			}
		})
	})
}

const goToHome = () => {
	uni.switchTab({
		url: '/pages/index/index'
	})
}

const goToPasswordLogin = () => {
	uni.navigateTo({
		url: '/pages/auth/login'
	})
}

const goToRegister = () => {
	uni.navigateTo({
		url: '/pages/auth/face-register'
	})
}

const goToDebug = () => {
	uni.navigateTo({
		url: '/pages/test/camera-debug'
	})
}

const goToSimpleTest = () => {
	uni.navigateTo({
		url: '/pages/test/simple-camera'
	})
}

const goToPureTest = () => {
	uni.navigateTo({
		url: '/pages/test/pure-html5-camera'
	})
}

const goToCaptureTest = () => {
	uni.navigateTo({
		url: '/pages/test/camera-capture-test'
	})
}

const goToCanvasTest = () => {
	uni.navigateTo({
		url: '/pages/test/canvas-test'
	})
}
</script>

<style lang="scss" scoped>
.face-login-page {
	min-height: 100vh;
	background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.content-container {
	padding: 40px 30px 30px;
	min-height: calc(100vh - 88px);
}

.header-section {
	text-align: center;
	margin-bottom: 40px;
}

.icon-container {
	width: 80px;
	height: 80px;
	margin: 0 auto 20px;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 40px;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 8px 24px rgba(102, 126, 234, 0.3);
}

.face-icon {
	font-size: 36px;
	color: #ffffff;
}

.main-title {
	display: block;
	font-size: 28px;
	font-weight: 700;
	color: #333333;
	margin-bottom: 8px;
}

.sub-title {
	display: block;
	font-size: 16px;
	color: #666666;
	font-weight: 300;
}

.input-section {
	margin-bottom: 40px;
}

.input-group {
	background: #ffffff;
	border-radius: 16px;
	padding: 24px;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.input-label {
	display: block;
	font-size: 16px;
	font-weight: 600;
	color: #333333;
	margin-bottom: 12px;
}

.input-field {
	width: 100%;
	height: 48px;
	background: #f8f9fa;
	border: 2px solid #e9ecef;
	border-radius: 12px;
	padding: 0 16px;
	font-size: 16px;
	color: #333333;
	transition: all 0.3s ease;

	&:focus {
		border-color: #007AFF;
		background: #ffffff;
		outline: none;
	}

	&.input-error {
		border-color: #ff4d4f;
		background: #fff2f0;
	}
}

.error-text {
	display: block;
	font-size: 14px;
	color: #ff4d4f;
	margin-top: 8px;
	font-weight: 500;
}

.status-section {
	margin-bottom: 40px;
}

.status-card {
	background: #ffffff;
	border-radius: 20px;
	padding: 30px 20px;
	text-align: center;
	box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
	border: 2px solid transparent;
	transition: all 0.3s ease;
	
	&.status-idle {
		border-color: #e0e0e0;
	}
	
	&.status-scanning {
		border-color: #007AFF;
		background: linear-gradient(135deg, #f0f8ff 0%, #e6f3ff 100%);
	}
	
	&.status-success {
		border-color: #52c41a;
		background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
	}
	
	&.status-failed {
		border-color: #ff4d4f;
		background: linear-gradient(135deg, #fff2f0 0%, #ffccc7 100%);
	}
}

.status-icon {
	font-size: 48px;
	margin-bottom: 16px;
}

.status-text {
	display: block;
	font-size: 18px;
	font-weight: 600;
	color: #333333;
	margin-bottom: 8px;
}

.error-detail {
	display: block;
	font-size: 14px;
	color: #ff4d4f;
}

.action-section {
	margin-bottom: 40px;
}

.btn {
	width: 100%;
	height: 56px;
	border-radius: 16px;
	font-size: 16px;
	font-weight: 600;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 8px;
	transition: all 0.3s ease;
	margin-bottom: 16px;
	
	&.btn-primary {
		background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
		color: #ffffff;
		box-shadow: 0 6px 20px rgba(0, 122, 255, 0.3);
		
		&:hover {
			transform: translateY(-2px);
			box-shadow: 0 8px 24px rgba(0, 122, 255, 0.4);
		}
	}
	
	&.btn-secondary {
		background: rgba(0, 0, 0, 0.1);
		color: #333333;
		border: 1px solid rgba(0, 0, 0, 0.2);
		
		&:hover {
			background: rgba(0, 0, 0, 0.15);
		}
	}
	
	&.btn-outline {
		background: transparent;
		color: #007AFF;
		border: 2px solid #007AFF;
		
		&:hover {
			background: #007AFF;
			color: #ffffff;
		}
	}
}

.btn-icon {
	font-size: 18px;
}

.alternative-section {
	margin-bottom: 30px;
}

.divider {
	display: flex;
	align-items: center;
	margin-bottom: 20px;
}

.divider-line {
	flex: 1;
	height: 1px;
	background: #e0e0e0;
}

.divider-text {
	padding: 0 16px;
	font-size: 14px;
	color: #999999;
}

.alternative-buttons {
	display: flex;
	gap: 12px;
}

.alt-btn {
	flex: 1;
	height: 48px;
	font-size: 14px;
}

.register-hint {
	text-align: center;
}

.debug-links {
	text-align: center;
	margin-top: 12px;
	padding-top: 12px;
	border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.hint-text {
	color: #666666;
	font-size: 14px;
}

.hint-link {
	color: #007AFF;
	font-size: 14px;
	font-weight: 600;
	margin-left: 8px;
	text-decoration: underline;
}

.camera-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 9999;
	display: flex;
	align-items: flex-end;
}

.modal-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
}

.modal-content {
	position: relative;
	width: 100%;
	height: 80vh;
	background: #000000;
	border-radius: 20px 20px 0 0;
	overflow: hidden;
}
</style>